/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.base.web.customer;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.collect.SetUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.customer.CustomerContact;
import com.jeesite.modules.base.entity.customer.CustomerData;
import com.jeesite.modules.base.entity.customer.CustomerShowroom;
import com.jeesite.modules.base.entity.customerdataconfig.CustomerDataconfig;
import com.jeesite.modules.base.entity.guarantor.Guarantor;
import com.jeesite.modules.base.entity.warehouse.Twarehouse;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.customerdataconfig.CustomerDataconfigService;
import com.jeesite.modules.base.service.guarantor.GuarantorService;
import com.jeesite.modules.base.service.warehouse.TwarehouseService;
import com.jeesite.modules.custom.enumInfo.warhouseNatureEnum;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 客户Controller
 *
 * @author lv
 * @version 2021-02-25
 */
@Controller
@RequestMapping(value = "${adminPath}/base/customer/customer")
public class CustomerController extends BaseController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private GuarantorService guarantorService;
    @Autowired
    private UserService userService;
    @Autowired
    private CustomerDataconfigService customerDataconfigService;
    @Autowired
    private TwarehouseService warehouseService;

    /**
     * 获取数据
     */
    @ModelAttribute
    public Customer get(String customerId, boolean isNewRecord) {
        return customerService.get(customerId, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("base:customer:customer:view")
    @RequestMapping(value = {"list", ""})
    public String list(Customer customer, Model model) {
        model.addAttribute("listUser", userService.findList(new User()));
        model.addAttribute("customer", customer);
        return "modules/base/customer/customerList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("base:customer:customer:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public List < Customer > listData(Customer customer) {
        if (StringUtils.isBlank(customer.getParentCode())) {
            customer.setParentCode(Customer.ROOT_CODE);
        }
        if (StringUtils.isNotBlank(customer.getCustomerId())) {
            customer.setParentCode(null);
        }
        if (StringUtils.isNotBlank(customer.getCustomerName())) {
            customer.setParentCode(null);
        }
        if (StringUtils.isNotBlank(customer.getCustomerNameAbbreviation())) {
            customer.setParentCode(null);
        }
        if (StringUtils.isNotBlank(customer.getRemarks())) {
            customer.setParentCode(null);
        }
        List < Customer > list = customerService.findList(customer);
        return list;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("base:customer:customer:view")
    @RequestMapping(value = "form")
    public String form(Customer customer, Model model) {
        // 创建并初始化下一个节点信息
        customer = createNextNode(customer);
        // 资料信息默认配置
        List < CustomerDataconfig > listDataConfig = customerDataconfigService.findList(new CustomerDataconfig());
        if (customer.getIsNewRecord()) {
            List < CustomerData > listData = new ArrayList <>();
            for (CustomerDataconfig customerDataconfig : listDataConfig) {
                CustomerData customerData = new CustomerData();
                customerData.setDataName(customerDataconfig.getDataconId());
                customerData.setRequired(customerDataconfig.getDataconRequire());
                if ("1".equals(customerDataconfig.getDataconRequire())) {
                    customerData.setRequiredText("是");
                } else {
                    customerData.setRequiredText("否");
                }
                listData.add(customerData);
            }
            customer.setCustomerDataList(listData);
        } else {
            for (CustomerData customerData : customer.getCustomerDataList()) {
                if ("1".equals(customerData.getRequired())) {
                    customerData.setRequiredText("是");
                } else {
                    customerData.setRequiredText("否");
                }
            }
        }
        CustomerDataconfig dataconfig = new CustomerDataconfig();
        dataconfig.setDataconId("");
        dataconfig.setDataconName("");
        dataconfig.setDataconRequire("");
        listDataConfig.add(dataconfig);
        model.addAttribute("listDataConfig", listDataConfig);
        model.addAttribute("listUser", userService.findList(new User()));
        model.addAttribute("listGuar", guarantorService.findList(new Guarantor()));
        model.addAttribute("customer", customer);
        return "modules/base/customer/customerForm";
    }

    /**
     * 查看表单详情
     */
    @RequiresPermissions("base:customer:customer:view")
    @RequestMapping(value = "detail")
    public String detail(Customer customer, Model model) {
        // 创建并初始化下一个节点信息
        customer = createNextNode(customer);
        List < CustomerShowroom > listRooms = ListUtils.newArrayList();
        List < Twarehouse > listWarehouse = warehouseService.findList(new Twarehouse());
        for (Twarehouse warehouse : listWarehouse) {
            if (customer.getCustomerId().equals(warehouse.getCustomer()) &&
                    warhouseNatureEnum.LEASE_SHOWROOM.getCode().equals(warehouse.getProperty())
                    || warhouseNatureEnum.OWN_SHOWROOM.getCode().equals(warehouse.getProperty())) {
                CustomerShowroom showroom = new CustomerShowroom();
                showroom.setShowroomName(warehouse.getWarehouseName());
                showroom.setShowroomType(warehouse.getProperty());
                showroom.setAcreage(warehouse.getAcreage());
                showroom.setRemarks(warehouse.getRemarks());
                listRooms.add(showroom);
            }
        }
        customer.setCustomerShowroomList(listRooms);

        model.addAttribute("listDataConfig", customerDataconfigService.findList(new CustomerDataconfig()));
        model.addAttribute("listUser", userService.findList(new User()));
        model.addAttribute("listGuar", guarantorService.findList(new Guarantor()));
        model.addAttribute("customer", customer);
        return "modules/base/customer/customerDetail";
    }

    /**
     * 创建并初始化下一个节点信息，如：排序号、默认值
     */
    @RequiresPermissions("base:customer:customer:edit")
    @RequestMapping(value = "createNextNode")
    @ResponseBody
    public Customer createNextNode(Customer customer) {
        if (StringUtils.isNotBlank(customer.getParentCode())) {
            customer.setParent(customerService.get(customer.getParentCode()));
        }
		/*if (customer.getIsNewRecord()) {
			Customer where = new Customer();
			where.setParentCode(customer.getParentCode());
			Customer last = customerService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				customer.setTreeSort(last.getTreeSort() + 30);
				customer.setCustomerId(IdGen.nextCode(last.getCustomerId()));
			}else if (customer.getParent() != null){
				customer.setCustomerId(customer.getParent().getCustomerId() + "001");
			}
		}*/
        // 以下设置表单默认数据
        if (customer.getTreeSort() == null) {
            customer.setTreeSort(Customer.DEFAULT_TREE_SORT);
        }
        return customer;
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("base:customer:customer:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated Customer customer) {
        // 联系人信息
        int contactCode = 0;
        List < CustomerContact > listCustomer = customer.getCustomerContactList();
        for (CustomerContact customerContact : listCustomer) {
            if (StringUtils.isNotBlank(customerContact.getContactId()) && customerContact.getContactId().length() < 10) {
                customerContact.setContactId("");
            }
            if ("1".equals(customerContact.getMainFlag())) {
                contactCode++;
            }
        }
        if (contactCode != 1) {
            return renderResult(Global.FALSE, text("联系人信息必须有一个为主要联系人！"));
        }

        // 展厅信息
        List < CustomerShowroom > listRoom = customer.getCustomerShowroomList();
        for (CustomerShowroom customerShowroom : listRoom) {
            if (StringUtils.isNotBlank(customerShowroom.getShowroomId()) && customerShowroom.getShowroomId().length() < 10) {
                customerShowroom.setShowroomId("");
            }
        }

        // 资料信息
        int dataCode = 0;
        int setNameCount = 0;
        Set < String > setName = SetUtils.newHashSet();
        List < CustomerData > listData = customer.getCustomerDataList();
        for (CustomerData customerData : listData) {
            if (StringUtils.isNotBlank(customerData.getDataId()) && customerData.getDataId().length() < 10) {
                customerData.setDataId("");
            }
            if (!CustomerData.STATUS_DELETE.equals(customerData.getStatus())) {
                setName.add(customerData.getDataName());
                setNameCount++;
            }
        }
        if (setName.size() == 0) {
            return renderResult(Global.FALSE, text("准入资料明细必须存在！"));
        }
        if (setName.size() != setNameCount) {
            return renderResult(Global.FALSE, text("准入资料明细存在重复值！"));
        }
        customerService.save(customer);
        return renderResult(Global.TRUE, text("保存客户成功！"));
    }

    /**
     * 停用数据
     */
    @RequiresPermissions("base:customer:customer:edit")
    @RequestMapping(value = "disable")
    @ResponseBody
    public String disable(Customer customer) {
        Customer where = new Customer();
        where.setStatus(Customer.STATUS_NORMAL);
        where.setParentCodes("," + customer.getId() + ",");
        long count = customerService.findCount(where);
        if (count > 0) {
            return renderResult(Global.FALSE, text("该客户包含未停用的子客户！"));
        }
        customer.setStatus(Customer.STATUS_DISABLE);
        customerService.updateStatus(customer);
        return renderResult(Global.TRUE, text("停用客户成功"));
    }

    /**
     * 启用数据
     */
    @RequiresPermissions("base:customer:customer:edit")
    @RequestMapping(value = "enable")
    @ResponseBody
    public String enable(Customer customer) {
        customer.setStatus(Customer.STATUS_NORMAL);
        customerService.updateStatus(customer);
        return renderResult(Global.TRUE, text("启用客户成功"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("base:customer:customer:delete")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(Customer customer) {
        customerService.delete(customer);
        return renderResult(Global.TRUE, text("删除客户成功！"));
    }

    /**
     * 获取树结构数据
     *
     * @param excludeCode 排除的Code
     * @param isShowCode  是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
     * @return
     */
    @RequiresPermissions("base:customer:customer:view")
    @RequestMapping(value = "treeData")
    @ResponseBody
    public List < Map < String, Object > > treeData(String excludeCode, String isShowCode) {
        List < Map < String, Object > > mapList = ListUtils.newArrayList();
        List < Customer > list = customerService.findList(new Customer());
        for (int i = 0; i < list.size(); i++) {
            Customer e = list.get(i);
            // 过滤非正常的数据
            if (!Customer.STATUS_NORMAL.equals(e.getStatus())) {
                continue;
            }
            // 过滤被排除的编码（包括所有子级）
            if (StringUtils.isNotBlank(excludeCode)) {
                if (e.getId().equals(excludeCode)) {
                    continue;
                }
                if (e.getParentCodes().contains("," + excludeCode + ",")) {
                    continue;
                }
            }
            Map < String, Object > map = MapUtils.newHashMap();
            map.put("id", e.getId());
            map.put("pId", e.getParentCode());
            map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getCustomerId(), e.getCustomerName()));
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 修复表结构相关数据
     */
    @RequiresPermissions("base:customer:customer:edit")
    @RequestMapping(value = "fixTreeData")
    @ResponseBody
    public String fixTreeData(Customer customer) {
        if (!UserUtils.getUser().isAdmin()) {
            return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
        }
        customerService.fixTreeData();
        return renderResult(Global.TRUE, "数据修复成功");
    }


    @RequiresPermissions("base:supplier:supplier:edit")
    @RequestMapping(value = "checkAbbreviation")
    @ResponseBody
    public String checkAbbreviation(String oldCustomerNameAbbreviation, String customerNameAbbreviation) {
        Customer customer = new Customer();
        customer.setCustomerNameAbbreviation(customerNameAbbreviation);
        if (customerNameAbbreviation != null && customerNameAbbreviation.equals(oldCustomerNameAbbreviation)) {
            return Global.TRUE;
        } else if (customerNameAbbreviation != null && customerService.getByAbbreviation(customer) == null) {
            return Global.TRUE;
        }
        return Global.FALSE;
    }


}